/************************************************
* 文件描述: 程序主进程
* 待完善:
* 待优化:
* 修改日期：2020.11.04
* 修改内容：
*   创建  HZH
*************************************************/
#include "mainwindow.h"
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <QScrollBar>
#include <QPainterPath>
#include "highlight-effect.h"
#include "ui_mainwindow.h"
#include "globaldata.h"
#include <KWindowEffects>
#include <gsettingmonitor.h>

/* 适配组内SDK */
#include "windowmanage.hpp"

//gsetting获取主题样式关键字
namespace  GSETTINGCONST{
const QByteArray FITTHEMEWINDOW = "org.ukui.style";
// 62623 【103843】【服务与支持】侧边栏无法与系统透明度同步
const QByteArray FITCONTROLTRANS = "org.ukui.control-center.personalise";
const QByteArray UKUI_STYLE = "org.ukui.style";
const QString UKUI_FONT_SIZE = "systemFontSize";
// const QString UKUI_FONT = "systemFont";
const QString UKUI_FONT = "system-font";
}
enum class TabName : int
{
    INTRO = 0,
    MESSAGE,
    CONTACT,
    GUIDANCE,
    CUSTOMER,
};
/************************************************
* 函数名称：MainWindow
* 功能描述：构造函数
* 输入参数：无
* 输出参数：无
* 修改日期：2020.11.04
* 修改内容：
*   创建  HZH
*
*************************************************/
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    kabase::WindowManage::getWindowId(&m_windowId);

    ui->setupUi(this);
    //单例运行
    checkSingle();

    getSysVersion();

    m_daemonIpcDbus = new DaemonIpcDbus();

    m_localInfo = new LocalInfo(this);
    m_localInfo->getLocalInfo();

    initWidgetStyle();

    this->setWindowTitle(tr("Services and Supports"));

    initGsetting();

    this->setAutoFillBackground(true);
    this->setBackgroundRole(QPalette::Window);
    this->setProperty("useSystemStyleBlur",true);
    this->setAttribute(Qt::WA_TranslucentBackground,true);
    this->setWindowTitle(tr("Services and Supports"));

    /* 适配kysdk的窗管 */
    ::kabase::WindowManage::removeHeader(this);
}
/************************************************
* 函数名称：MainWindow
* 功能描述：析构函数
* 输入参数：无
* 输出参数：无
* 修改日期：2020.11.04
* 修改内容：
*   创建  HZH
*
*************************************************/
MainWindow::~MainWindow()
{
    ::close(fd);
    if (m_daemonIpcDbus != nullptr)
    {
        delete m_daemonIpcDbus;
    }
}

/************************************************
* 函数名称：单例模式
* 功能描述：检查是否单例运行
* 输入参数：
* 输出参数：
* 修改日期：2020.11.04
* 修改内容：
*   创建  HZH
*
*************************************************/
void MainWindow::checkSingle()
{
    QStringList homePath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);

    fd = open(QString(homePath.at(0) + "/.config/kylin-service-support%1.lock").arg(getenv("DISPLAY")).toUtf8().data(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);

    if (fd < 0)
    {
        exit(1);
    }

    if (lockf(fd, F_TLOCK, 0))
    {
        qDebug()<<"Can't lock single file, kylin-service-support is already running!";
        exit(0);
    }


}

/************************************************
* 函数名称：gsetting初始化
* 功能描述：
* 输入参数：
* 输出参数：
* 修改日期：2020.10.12
* 修改内容：
*   创建  HZH
*
*************************************************/
void MainWindow::initGsetting()
{
    GlobalData::getInstance();
   
    setThemeStyle(); // 主题
    changeTrans();   // 透明度
    initFontSize();
    initFont();

    connect(GlobalData::getInstance(), &GlobalData::sigFontSizeChange, this, &MainWindow::initFontSize);
    connect(GlobalData::getInstance(), &GlobalData::sigFontNameChange, this, &MainWindow::initFont);
    connect(GlobalData::getInstance(), &GlobalData::sigTransparency, [=](){
        m_tran = GlobalData::getInstance()->getTransparencyData();
        ui->m_widget->changeTrans(m_tran);
    });
    connect(GlobalData::getInstance(), &GlobalData::sigTheme, this, &MainWindow::setThemeStyle);

    return;

}

void MainWindow::changeTrans()
{
    m_tran = GlobalData::getInstance()->getTransparencyData();
    ui->m_widget->changeTrans(m_tran);

    qDebug() << "透明度调整为：" << m_tran;
}

/************************************************
* 函数名称：setThemeStyle
* 功能描述：主题样式设计
* 输入参数：
* 输出参数：
* 修改日期：2020.10.12
* 修改内容：
*   创建  HZH
*
*************************************************/
void MainWindow::setThemeStyle()
{
    QString nowThemeStyle = GlobalData::getInstance()->getThemeData();
    
    qDebug() << "设置程序主题模式为" << nowThemeStyle;

    this->changePageForTheme(nowThemeStyle);
    this->repaint();
}

void MainWindow::initFontSize()
{
    //启动时设置字号
    this->setQSSFontSize();
}

void MainWindow::initFont()
{
    this->setQSSFont(GlobalData::getInstance()->getFontNameData());
}
/************************************************
* 函数名称：pullUpWindow
* 功能描述：窗口最小化时，点击程序图标，主窗口拉起
* 输入参数：
* 输出参数：
* 修改日期：2020.12.02
* 修改内容：
*   创建  HZH
*
*************************************************/
void MainWindow::pullUpWindow()
{
    qDebug()<<"MainWindow::pullUpWindow  iswindowminized:" << this->isMinimized();

    this->closeAboutWin();

    if(!this->isActiveWindow())
    {
        this->hide();
        this->show();
        ::kabase::WindowManage::setMiddleOfScreen(this);
    }

    this->showNormal();
    this->raise();
    this->activateWindow();
}
/************************************************
* 函数名称：getSysVersion
* 功能描述：获取系统版本
* 输入参数：
* 输出参数：
* 修改日期：2021.01.06
* 修改内容：
*   创建  HZH
*
*************************************************/
void MainWindow::getSysVersion()
{
    qDebug() << "开始获取系统版本信息";
    string os_info = ": ";
    QString system_info;
    QString system_name;
    QString system_version_id;
    string s;
    ifstream fp("/etc/os-release");
    if (!fp)
    {
        system_info = "None";
        m_multiFunc = false;
    }
    else
    {
        while (getline(fp,s))
        {
            string::size_type idx;
            idx = s.find("=");
            if (idx == string::npos)
            {
                //不存在
                m_multiFunc = false;
            }
            else
            {
                string str2 = s.substr(0,idx);
                if (str2 == "NAME")
                {
                    system_name = QString::fromStdString(s.substr(5));
                    if(system_name.contains("Kylin",Qt::CaseInsensitive))//仅应用于麒麟V10系列产品
                    {
                        m_multiFunc = true;
                    }
                    else
                    {
                        m_multiFunc = false;
                    }
                }
                else if(str2 =="VERSION_ID")
                {
                    system_version_id = QString::fromStdString(s.substr(11));
                    if(system_version_id.contains("v10",Qt::CaseInsensitive))
                    {
                        m_multiFunc = true;
                    }
                    else
                    {
                        m_multiFunc = false;
                    }
                }
            }
        }
    }
}
void MainWindow::initWidgetStyle()
{
    initWidgetSize();

    initWidgetBasicLayout();

    initWidgetLayout();
}
void MainWindow::closeMainWidget()
{
    if(m_pMenu->hasAboutWindow())
    {
        m_pMenu->closeAboutWindow();
    }
    this->close();
}
void MainWindow::initWidgetSize()
{
    QRect availableGeometry = qApp->primaryScreen()->availableGeometry();
    this->move((availableGeometry.width()-this->width())/2, (availableGeometry.height()-this->height())/2);
}
void MainWindow::initWidgetBasicLayout()
{
    ui->m_titleIconBtn->setIcon(QIcon::fromTheme("kylin-service-support"));
    ui->m_titleIconBtn->setIconSize(QSize(24,24));
    ui->m_titleIconBtn->setFixedSize(QSize(24,24));
    QString btnStyle = "QPushButton{border:0px;border-radius:4px;background:transparent;}"
                       "QPushButton:Hover{border:0px;border-radius:4px;background:transparent;}"
                       "QPushButton:Pressed{border:0px;border-radius:4px;background:transparent;}";
    ui->m_titleIconBtn->setStyleSheet(btnStyle);

    ui->m_ptittleLabel->setFixedSize(160,22);

    m_titleText = tr("Services and Supports");
    ui->m_ptittleLabel->setText(m_titleText);
    ui->m_ptittleLabel->setObjectName("titleLable");
    ui->m_ptittleLabel->setAlignment(Qt::AlignVCenter);

    ui->m_ptittleLabel->setStyleSheet({"background:transparent"});

    m_pBar = new KNavigationBar(this);
    QStandardItem * item1 = new QStandardItem(QIcon::fromTheme("view-dual-symbolic"),tr("Intro"));
    QStandardItem * item2 = new QStandardItem(QIcon::fromTheme("messaging-app-symbolic"),tr("Message"));
    QStandardItem * item3 = new QStandardItem(QIcon::fromTheme("call-stop-symbolic"),tr("Contact"));
    QStandardItem * item4 = new QStandardItem(QIcon::fromTheme("ukui-self-help-symbolic"),tr("Guidance"));
    QStandardItem * item5 = new QStandardItem(QIcon::fromTheme("audio-headset-symbolic"),tr("Customer"));

    m_pBar->addItem(item1);
    m_pBar->addItem(item2);
    m_pBar->addItem(item3);
    m_pBar->addItem(item4);
    m_pBar->addItem(item5);

    ui->m_navigateLayout->addWidget(m_pBar);
    
    QModelIndex index = m_pBar->model()->index(0,0);
    m_pBar->listview()->setCurrentIndex(index);

    connect(m_pBar->listview(),&QListView::clicked,this,
            [=](const QModelIndex &index){
        QString curIndexName = index.data().toString();
        changPage(curIndexName);
    });

    //右对话框背景
    ui->m_showBox->setFixedSize(760,640);
    ui->m_showBox->setObjectName("showBox");
    ui->m_showBox->setAutoFillBackground(true);
    ui->m_showBox->setBackgroundRole(QPalette::Base);

    ui->m_btnTitleWidget->setFixedSize(760,40);
    ui->m_btnTitleWidget->setAutoFillBackground(true);
    ui->m_btnTitleWidget->setBackgroundRole(QPalette::Base);

    m_pstackWidget = new QStackedWidget(ui->m_showBox);

    m_mainPage = new IntroPageStyle(this);
    m_messagePage = new MessagePageStyle(this);
    m_contactPage = new ContactPageStyle(this);
    m_diySupportPage = new GuidancePageStyle(this);
        //TODO:
        //需求未确定，暂不开放
        //    m_webPage = new WebBrowser();

    m_pMenu  = new menuModule(this);

    connect(m_pMenu,&menuModule::menuModuleClose,[=](){
        if(m_pMenu->hasAboutWindow())
        {
            m_pMenu->closeAboutWindow();
        }
        this->close();
    });

    m_pwidgetMinBtn =new QPushButton(this);//最小化按钮
    m_pwidgetMinBtn->setIcon(QIcon::fromTheme("window-minimize-symbolic"));//主题库的最小化图标
    m_pwidgetMinBtn->setProperty("isWindowButton", 0x1);

    m_pwidgetMinBtn->setProperty("useIconHighlightEffect", 0x2);

    m_pwidgetMinBtn->setFlat(true);
    m_pwidgetMinBtn->setFixedSize(30, 30);
    m_pwidgetMinBtn->setIconSize(QSize(16, 16));

    connect(m_pwidgetMinBtn,&QPushButton::clicked,this,[=]{
        this->setWindowState(Qt::WindowMinimized);
    });

    m_pwidgetCloseBtn =new QPushButton(this);//关闭按钮
    m_pwidgetCloseBtn->setIcon(QIcon::fromTheme("window-close-symbolic"));
    m_pwidgetCloseBtn->setObjectName("widgetClose");
    m_pwidgetCloseBtn->setProperty("isWindowButton", 0x2) ;
    m_pwidgetCloseBtn->setProperty("useIconHighlightEffect", 0x8);

    m_pwidgetCloseBtn->setFlat(true);

    m_pwidgetCloseBtn->setFixedSize(30, 30);
    m_pwidgetCloseBtn->setIconSize(QSize(16, 16));

    connect(m_pwidgetCloseBtn,&QPushButton::clicked,this,&MainWindow::closeMainWidget);

    ui->m_btnTitle->setSpacing(0);
    ui->m_btnTitle->addStretch();
    ui->m_btnTitle->addSpacing(4);
    ui->m_btnTitle->addWidget(m_pMenu->getMenuBtn());
    ui->m_btnTitle->addSpacing(4);
    ui->m_btnTitle->addWidget(m_pwidgetMinBtn);
    ui->m_btnTitle->addSpacing(4);
    ui->m_btnTitle->addWidget(m_pwidgetCloseBtn);
}

void MainWindow::changPage(const QString& curName)
{
    if (!curName.compare(tr("Intro")))
    {
        gotoMainPage();
    }else if (!curName.compare(tr("Message")))
    {
        gotoMessagePage();
    }else if (!curName.compare(tr("Contact")))
    {
        gotoContactPage();
    }else if (!curName.compare(tr("Guidance")))
    {
        gotoDIYPage();
    }else if (!curName.compare(tr("Customer")))
    {
        gotoOnlinePage();
    }
    else
    {
        qCritical() << "错误的判断分支！";
        gotoMainPage();
    }
}

void MainWindow::gotoMainPage()
{
    m_pstackWidget->setCurrentIndex(static_cast<int>(PageNum::MAINPAGINDEX));
    m_currentPageIndex = static_cast<int>(PageNum::MAINPAGINDEX);
}
void MainWindow::gotoMessagePage()
{
    m_pstackWidget->setCurrentIndex(static_cast<int>(PageNum::MESSAGEPAGEINDEX));
    m_currentPageIndex = static_cast<int>(PageNum::MESSAGEPAGEINDEX);
}
void MainWindow::gotoOnlinePage()
{
    /* sdk打点：跳转在线客服 */
    GlobalData::SDKPointJumpOnlineService();
    
    QDesktopServices::openUrl(QUrl("https://webchat-bj.clink.cn/chat.html?accessId=8b626ce9-8d56-4b68-b6f9-de357a088258&language=zh_CN"));
    //TODO:
    //需求未确定，暂不开放该功能
//    m_pstackWidget->setCurrentIndex(static_cast<int>(PageNum::WEBPAGEINDEX));
//    m_currentPageIndex = static_cast<int>(PageNum::WEBPAGEINDEX);
}
void MainWindow::gotoContactPage()
{
    m_pstackWidget->setCurrentIndex(static_cast<int>(PageNum::TEAMPAGEINDEX));
    m_currentPageIndex = static_cast<int>(PageNum::TEAMPAGEINDEX);
}
void MainWindow::gotoDIYPage()
{
    m_pstackWidget->setCurrentIndex(static_cast<int>(PageNum::DIYPAGEINDEX));
    m_currentPageIndex = static_cast<int>(PageNum::DIYPAGEINDEX);
}

void MainWindow::changePageForTheme(const QString& str)
{
    m_currentTheme = str;
    m_messagePage->changePageForTheme(m_currentTheme);
//    m_diySupportPage->changePageForTheme(m_currentTheme);
//TODO:
    //    m_mainPage->changePageForTheme(m_currentTheme);
    m_pMenu->changePageForTheme(m_currentTheme);
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_F1)
    {
        if(!m_daemonIpcDbus->daemonIsNotRunning()){
            m_daemonIpcDbus->showGuide("Services-and-Supports");
        }
    }
}
void MainWindow::closeAboutWin()
{
    if(m_pMenu->hasAboutWindow())
    {
        m_pMenu->closeAboutWindow();
    }
    else
    {
        return;
    }
}

void MainWindow::setQSSFontSize()
{
    changeTitleFont(GlobalData::getInstance()->getFontSize14px());
    m_pMenu->changeFont(GlobalData::getInstance()->getFontSize14px());
    m_mainPage->changeFont(GlobalData::getInstance()->getFontSize14px());
    m_messagePage->changeFont(GlobalData::getInstance()->getFontSize14px());
    m_contactPage->changeFont(GlobalData::getInstance()->getFontSize14px());
    m_diySupportPage->changeFont(GlobalData::getInstance()->getFontSize14px());
}

void MainWindow::setQSSFont(const QString& currentFont)
{
    qDebug() << currentFont;

    QFont font;
    font.setFamily(currentFont);

    changeTitleFont(font);
    //右上角菜单
    m_pMenu->changeFont(font);
//TODO:
    m_mainPage->changeFont(font);
    m_messagePage->changeFont(font);
    m_contactPage->changeFont(font);
    m_diySupportPage->changeFont(font);
}

void MainWindow::initWidgetLayout()
{
    m_pstackWidget->setFixedHeight(600);
    m_pstackWidget->setContentsMargins(0, 0, 0, 0);
    m_pstackWidget->addWidget(m_mainPage);
    m_pstackWidget->addWidget(m_messagePage);
    m_pstackWidget->addWidget(m_contactPage);
    m_pstackWidget->addWidget(m_diySupportPage);
//    TODO:
//    未确认需求，暂不开放
//        m_pstackWidget->addWidget(m_webPage);

    ui->m_showBoxLayout->addWidget(m_pstackWidget);
}

void MainWindow::changeTitleFont(QFont font)
{
    ui->m_ptittleLabel->setFont(font);
    QString text = m_titleText;
    // 过长时进行省略显示
    QFontMetrics fontmts = QFontMetrics(font);
    int dif = fontmts.width(m_titleText) - 150;
    if (dif > 0) {
        ui->m_ptittleLabel->setToolTip(text);
        text = fontmts.elidedText(m_titleText, Qt::ElideRight, 150);
    }
    ui->m_ptittleLabel->setText(text);
    
    return;
}